import { reqGetCode, reqUserRegister, reqLogout, reqUserInfo, reqLoginout } from "@/api";
import {setToken , getToken, removeToken} from "@/utils/token"
import { messages } from "vee-validate/dist/locale/zh_CN";

// home仓库 
const state = {
  code: "",
  token: localStorage.getItem('TOKEN'),
  userInfo: {},
};
const mutations = {
  // 注册业务
  GETCODE(state, code) {
    state.code = code;
  },

  // 登录业务
  USERLOGIN(state, token) {
    state.token = token;
  },

  // 接收token
  GETUSERINFO(state,userInfo){
    state.userInfo = userInfo
  },

  // 清除本地数据
  CLEAR(state){
    // 把仓库以及本地存储中相关信息清空
    state.token = '',
    state.userInfo = {},
    removeToken()
  }
};
const actions = {
  // 获取验证码
  async getCode({ commit }, phone) {
    // 验证码返回到了控制台上,省钱不发到用户手机上
    let result = await reqGetCode(phone);
    if (result.code == 200) {
      commit("GETCODE", result.data);
      return "ok";
    } else {
      return Promise.reject(new Error("faile"));
    }
  },

  // 用户注册
  async userRegister({ commit }, user) {
    let result = await reqUserRegister(user);
    if (result.code == 200) {
      return "ok";
    } else {
      return Promise.reject(new Error('请确认手机号是否重复,以及验证码是否输入输入正确'));
    }
  },

  // 登录业务
  async userLogin({ commit }, data) {
    let result = await reqLogout(data);
    // 服务器一般会下发token,需要通过token来找到对应的用户信息
    if (result.code == 200) {
      // 用户已经获取到了token,但是要本地持久化存储,不然刷新页面就会导致数据丢失
      commit("USERLOGIN", result.data.token);
      // 持久化存储token
      setToken(result.data.token)
      return "ok";
    } else {
      return Promise.reject(new Error());
    }
  },

  // 用token获取用户信息 
  async getUserInfo({commit}) {
    let result = await reqUserInfo()
    if(result.code == 200){
      commit('GETUSERINFO',result.data)
      return 'ok'
    }
  },

  // 退出登录业务
  async userLoginout({commit}){
    let result = await reqLoginout();
    // 清除本地数据
    if(result.code == 200){
      commit('CLEAR')
      return 'ok'
    }else{
      return Promise.reject(new Error(result.error))
    }
  }
};
const getters = {};

export default {
  state,
  mutations,
  actions,
  getters,
};
